import flet as ft

from data_tread import df_mean_to_value
from view import SensorView, AngleChart, data_to_line_chart_point
from api_sensor import *
from config import ProjectInfo, Product


def main(page: ft.Page):
    # region 功能函数
    def show_change():
        while ProjectInfo.Sensor_data_Send_state:
            data_df = ProjectInfo.sensor_data_mean_queue.get()
            sensor_view.show_data(data_df)
            if ProjectInfo.Sensor_data_Record_state:
                update_chart(data_df)

            # 更新页面
            page.update()

    def update_chart(df_data):
        sensor_value_dict = df_mean_to_value(df_data)
        angle_data = data_to_line_chart_point(sensor_value_dict)
        if angle_data:
            edit_text_a.value = str(angle_data["a_angel"])
            edit_text_b.value = str(angle_data["b_angel"])
            edit_text_t.value = str(angle_data["total_angle"])
            angle_chart.update()

    # endregion

    # region 事件
    def btn_search_click(e):

        page.run_thread(search_sensor)  # 搜索传感器
        if not ProjectInfo.Sensor_data_Send_state:
            ProjectInfo.Sensor_data_Send_state = True
        page.run_thread(receive_data_to_queue)  # 将传感器其的数据放入数据队列
        page.run_thread(get_sensor_data_to_mean)  # 获取传感器平均值
        page.run_thread(show_change)

        # ui_search_sensor(page, sensor_view)

    def close_alert(e):
        page.close(alter)

    def show_alert(msg):
        alter.title = ft.Text(msg)
        page.open(alter)

    def btn_start_record_click(e):
        # region 处理产品和传感器信息
        pip_label = t_id.value.strip()
        pip_name = t_name.value.strip()
        if not pip_label or not pip_name:
            show_alert("管道标识和管道名称不能为空")
            return
        for sensor in ProjectInfo.sensor_info_dict.values():
            if sensor.location == "A端":
                ProjectInfo.a_sensor_code_list.append(sensor.sensor_code)
            if sensor.location == "B端":
                ProjectInfo.b_sensor_code_list.append(sensor.sensor_code)
        if not ProjectInfo.a_sensor_code_list or not ProjectInfo.b_sensor_code_list:
            show_alert("请确保A端和B端都有传感器，并设置传感器的位置信息")
            return
        product = ProjectInfo.product
        product.name = pip_name
        product.label = pip_label
        if not product.id:
            insert_product_to_db(product)
            print(product)
        else:
            update_product_to_db(product)
            print(product)

        for sensor in ProjectInfo.sensor_info_dict.values():
            sensor.product_id = product.id
            if not sensor.id:
                insert_sensor_to_db(sensor)
            else:
                update_sensor_to_db(sensor)

        # endregion

        ProjectInfo.Sensor_data_Record_state = True
        ProjectInfo.a_agree_list = []
        ProjectInfo.b_agree_list = []
        page.run_thread(insert_raw_data_to_db)
        page.run_thread(insert_sensor_data_to_db)
        btn_stop_record.disabled = False
        btn_start_record.disabled = True

    def close_record(e):
        ProjectInfo.Sensor_data_Record_state = False
        btn_stop_record.disabled = True
        btn_start_record.disabled = False

    # endregion

    # 标题
    page.title = "管道弯制测量系统"
    t_id = ft.TextField(label="管道标识", width=200)
    t_name = ft.TextField(label="管道名称", width=200)
    btn_search = ft.ElevatedButton(text="搜索传感器", on_click=btn_search_click)
    btn_start_record = ft.ElevatedButton(text="开始记录", on_click=btn_start_record_click)
    btn_stop_record = ft.ElevatedButton(text="停止记录", disabled=True, on_click=close_record)
    edit_text_a = ft.TextField(label="A端角度", value="0", width=100)
    edit_text_b = ft.TextField(label="B端角度", value="0", width=100)
    edit_text_t = ft.TextField(label="弯制角度", value="0", width=100)
    # btn_test = ft.ElevatedButton(text="测试", on_click=btn_test_click)
    alter = ft.AlertDialog(
        title=ft.Text("信息"),
        actions=[ft.ElevatedButton("确定", on_click=close_alert)],
        modal=True
    )
    angle_chart = AngleChart()
    sensor_view = SensorView()
    ProjectInfo.product = Product()
    # sensor_chart = SensorChart()
    page.add(
        ft.Row(
            [t_id, t_name, btn_search, btn_start_record, btn_stop_record, edit_text_a, edit_text_b, edit_text_t],
        ),
        ft.Row([sensor_view]),
        ft.Row([angle_chart])
    )
    page.scroll = True
    page.update()


if __name__ == '__main__':
    ft.app(main)
